package com.gqh.weather.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gqh.weather.domain.dto.CcSchoolListData;
import com.gqh.weather.domain.dto.CcSchoolListResponse;
import com.gqh.weather.domain.dto.CcSchoolUpdateResponse;
import com.gqh.weather.domain.entity.CcSchoolStudentCount;
import com.gqh.weather.domain.entity.School;
import com.gqh.weather.domain.entity.Student;
import com.gqh.weather.domain.entity.Task;
import com.gqh.weather.exception.BusinessException;
import com.gqh.weather.exception.Result;
import com.gqh.weather.mapper.CcSchoolMapper;
import com.gqh.weather.mapper.CcSchoolStudentCountMapper;
import com.gqh.weather.mapper.CityMapper;
import com.gqh.weather.mapper.SchoolMapper;
import com.gqh.weather.mapper.StudentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 抽测学校管理服务类
 */
@Slf4j
@Service
public class CCSchoolService extends ServiceImpl<CcSchoolStudentCountMapper, CcSchoolStudentCount> {

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private CcSchoolMapper ccSchoolMapper;

    /**
     * 抽测学校列表查询
     *
     * @param citycode   城市码
     * @param taskId     任务id
     * @param matchState 匹配状态 0全部 1匹配 2不匹配
     * @param page       页数
     * @param count      每页数量
     * @param keyword    搜索关键字
     * @return 查询结果
     */
    public Result<CcSchoolListResponse> getCcSchoolList(String citycode, Integer taskId, Integer matchState,
                                                        Integer page, Integer count, String keyword) {
        try {
            // 验证任务是否存在
            Task task = taskService.getById(taskId);
            if (task == null) {
                throw new BusinessException("任务不存在");
            }

            // 获取城市代码列表
            List<String> codes = new ArrayList<>();
            codes.add(citycode);
            codes.addAll(cityMapper.selectChildrenCodesByCode(citycode));

            // 创建分页对象
            Page<CcSchoolListData> pageObj = new Page<>(page, count);

            // 查询数据
            Page<CcSchoolListData> resultPage = ccSchoolMapper.selectCcSchoolList(pageObj, codes, taskId, matchState, keyword);
            
            // 查询抽测匹配总数
            Integer allSccCount = ccSchoolMapper.selectAllSccCount(taskId);
            if (allSccCount == null) {
                allSccCount = 0;
            }

            // 构建分页结果
            CcSchoolListResponse response = new CcSchoolListResponse();
            response.setPage((int) resultPage.getCurrent());
            response.setCount((int) resultPage.getSize());
            response.setTotal(resultPage.getTotal());
            response.setData(resultPage.getRecords());
            response.setAllSccCount(allSccCount);

            return Result.success(response);

        } catch (Exception e) {
            log.error("查询抽测学校列表失败", e);
            return Result.error("查询失败");
        }
    }

    /**
     * 抽测学校修改
     *
     * @param taskId   任务id
     * @param schoolId 学校id
     * @param ccCount  抽测人数
     * @return 修改结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<CcSchoolUpdateResponse> updateCcSchool(Integer taskId, Integer schoolId, Integer ccCount) {
        try {
            // 验证任务是否存在
            Task task = taskService.getById(taskId);
            if (task == null) {
                return Result.error("任务不存在");
            }

            // 验证学校是否存在
            School school = schoolMapper.selectById(schoolId);
            if (school == null) {
                return Result.error("学校不存在");
            }

            // 验证任务状态
            if (task.getSchoolState() == 1) {
                return Result.error("学校已经锁定！");
            }

            // 查找或创建抽测记录
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CcSchoolStudentCount> wrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            wrapper.eq(CcSchoolStudentCount::getTaskId, taskId);
            wrapper.eq(CcSchoolStudentCount::getSchoolId, schoolId);
            wrapper.eq(CcSchoolStudentCount::getIsDeleted, 0);
            CcSchoolStudentCount ccRecord = getOne(wrapper);

            if (ccRecord == null) {
                // 创建新记录
                ccRecord = new CcSchoolStudentCount();
                ccRecord.setTaskId(taskId);
                ccRecord.setSchoolId(schoolId);
                ccRecord.setCcCount(ccCount);
                save(ccRecord);
            } else {
                // 更新现有记录
                ccRecord.setCcCount(ccCount);
                updateById(ccRecord);
            }

            // 获取导入学生数
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Student> studentWrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            studentWrapper.eq(Student::getTaskId, taskId);
            studentWrapper.eq(Student::getSchoolId, schoolId);
            studentWrapper.eq(Student::getIsDeleted, 0);
            int studentCount = studentMapper.selectCount(studentWrapper).intValue();

            // 获取任务中学校设置抽测总人数
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CcSchoolStudentCount> ccCountWrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            ccCountWrapper.eq(CcSchoolStudentCount::getTaskId, taskId);
            ccCountWrapper.eq(CcSchoolStudentCount::getIsDeleted, 0);
            List<CcSchoolStudentCount> ccCountList = list(ccCountWrapper);
            int totalCcCount = ccCountList.stream().mapToInt(CcSchoolStudentCount::getCcCount).sum();

            // 构建响应
            CcSchoolUpdateResponse response = new CcSchoolUpdateResponse();
            response.setTaskId(taskId);
            response.setSchoolId(schoolId);
            response.setCount(totalCcCount);

            // 导入人数大于等于抽测人数即为匹配，否则不匹配
            if (ccCount <= studentCount) {
                response.setState(1); // 匹配
            } else {
                response.setState(0); // 不匹配
            }

            return Result.success(response);

        } catch (Exception e) {
            log.error("修改抽测学校失败", e);
            return Result.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 抽测学校锁定
     *
     * @param taskId 任务id
     * @return 锁定结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> lockCcSchool(Integer taskId) {
        try {
            // 验证任务是否存在
            Task task = taskService.getById(taskId);
            if (task == null) {
                return Result.error("任务不存在");
            }

            // 更新任务的学校锁定状态
            task.setSchoolState(1);
            taskService.updateById(task);

            return Result.success(null);

        } catch (Exception e) {
            log.error("锁定抽测学校失败", e);
            return Result.error("锁定失败：" + e.getMessage());
        }
    }
}